<template>
  <el-dialog
    :title="handle == 'add' ? '新增开票' : handle == 'edit' ? '编辑开票' : '开票详情'"
    :visible.sync="show"
    width="1080px"
    append-to-body
    @close="dialogClose"
  >
    <el-form ref="formRef" :model="editForm" :rules="formRules" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属事业部" prop="department">
            <span v-if="handle == 'detail'">{{ editForm.department }}</span>
            <el-select
              v-else
              v-model="editForm.department"
              placeholder="选择所属事业部"
              clearable
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in divisionList"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="订单类型" prop="order_type">
            <span v-if="handle == 'detail'">{{ editForm.order_type }}</span>
            <el-radio-group
              v-else
              v-model="editForm.order_type"
              @change="changeOrderType"
            >
              <el-radio
                v-for="(item, index) in orderTypeList"
                :key="index"
                :label="item"
              />
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开票单位名称" prop="invoice_unit">
            <span v-if="handle == 'detail'">{{ editForm.invoice_unit }}</span>
            <el-select
              v-else
              v-model="editForm.invoice_unit"
              placeholder="选择开票单位"
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in invoiceUnitList"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开票类型" prop="invoice_type">
            <span v-if="handle == 'detail'">{{ editForm.invoice_type }}</span>
            <el-radio-group v-else v-model="editForm.invoice_type">
              <el-radio
                v-for="(item, index) in invoiceTypeList"
                :key="index"
                :label="item"
              />
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户" prop="customer_id">
            <span v-if="handle == 'detail'">{{ editForm.customer_name }}</span>
            <el-select
              v-else
              v-model="editForm.customer_id"
              filterable
              remote
              class="receivable"
              :clearable="false"
              placeholder="请检索"
              style="width: 100%"
              :remote-method="getCustomerList"
              @change="changeCustomer"
            >
              <el-option
                v-for="item in customerList"
                :key="item.customer_id"
                :label="item.name"
                :value="item.customer_id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="货物及应税劳务" prop="service_name">
            <span v-if="handle == 'detail'">{{ editForm.service_name }}</span>
            <el-select
              v-else
              v-model="editForm.service_name"
              placeholder="选择货物及应税劳务"
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in serviceList"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <div style="margin-bottom: 20px">
        <div v-if="handle != 'detail'" style="margin-bottom: 20px">
          <el-button type="primary" icon="el-icon-plus" @click="addData">新增</el-button>
        </div>
        <el-table :data="dataList" border style="width: 100%">
          <el-table-column label="序号" type="index" width="60" align="center" />
          <el-table-column label="合同名称" align="center">
            <template slot-scope="scope">
              <span
                v-if="handle == 'detail'"
                :style="showDetail ? 'color: #409eff; cursor: pointer' : ''"
                @click="handleContract(scope.row)"
              >
                {{ scope.row.contract_num }}
              </span>
              <el-select
                v-else
                v-model="scope.row.contract_id"
                placeholder="请选择"
                style="width: 100%"
                @change="(e) => changeReceipt(e, scope.$index)"
              >
                <el-option
                  v-for="item in contractList"
                  :key="item.contract_id"
                  :label="item.num"
                  :value="item.contract_id"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="回款编号" align="center">
            <template slot-scope="scope">
              <span v-if="handle == 'detail'">{{ scope.row.order_sn }} </span>
              <el-select
                v-else
                v-model="scope.row.order_sn"
                placeholder="请选择"
                :disabled="editForm.order_type == '先票后款'"
                style="width: 100%"
                @change="(e) => changeOrderSn(e, scope.$index)"
              >
                <el-option
                  v-for="(item, k) in scope.row.orderList"
                  :key="scope.row.contract_id + '_' + k"
                  :label="item.order_sn"
                  :value="item.order_sn"
                  :disabled="dataList.some((i) => i.order_sn == item.order_sn)"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="总金额" align="center" prop="total_money" width="130" />
          <el-table-column
            label="已开票金额"
            align="center"
            prop="used_money"
            width="130"
          />
          <el-table-column label="开票金额" align="center" width="150">
            <template slot-scope="scope">
              <span v-if="handle == 'detail'">{{ scope.row.money }}</span>
              <el-input-number
                v-else
                v-model="scope.row.money"
                type="number"
                :max="
                  parseFloat(scope.row.total_money || '0') -
                  parseFloat(scope.row.used_money || '0')
                "
                :min="0"
                :precision="2"
                :controls="false"
                placeholder="请输入"
                style="width: 100%"
              />
            </template>
          </el-table-column>
          <el-table-column
            v-if="handle != 'detail'"
            label="操作"
            align="center"
            width="80"
          >
            <template slot-scope="scope">
              <el-button
                type="danger"
                icon="el-icon-minus"
                size="small"
                circle
                @click="delData(scope.$index)"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户单位名称" prop="customer_unit">
            <span v-if="handle == 'detail'">{{ editForm.customer_unit }}</span>
            <el-input
              v-else
              v-model="editForm.customer_unit"
              placeholder="请输入客户单位名称"
              maxlength="100"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="型号规格" prop="specification_model">
            <span v-if="handle == 'detail'">{{ editForm.specification_model }}</span>
            <el-input
              v-else
              v-model="editForm.specification_model"
              placeholder="请输入型号规格"
              maxlength="100"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="纳税识别号" prop="pay_duty_number">
            <span v-if="handle == 'detail'">{{ editForm.pay_duty_number }}</span>
            <el-input
              v-else
              v-model="editForm.pay_duty_number"
              placeholder="请输入纳税识别号"
              maxlength="20"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开票金额" prop="invoice_money">
            {{ editForm.invoice_money }}元
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <span v-if="handle == 'detail'">{{ editForm.remark }}</span>
            <el-input
              v-else
              v-model="editForm.remark"
              type="textarea"
              :rows="{
                minRows: 2,
                maxRows: 4,
              }"
              placeholder="请输入备注"
              maxlength="200"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="附件" prop="attachment">
            <div v-if="handle == 'detail'">
              <img
                v-for="(i, k) in fileList"
                :key="k"
                :src="
                  i.split('.')[i.split('.').length - 1] == 'pdf'
                    ? require('@/assets/img/icon-pdf.png')
                    : i
                "
                class="atta-img"
                @click="previewImage(k)"
              />
            </div>
            <el-upload
              v-else
              ref="fileUpload"
              :action="crmFileSaveUrl"
              :headers="httpHeader"
              name="file[]"
              multiple
              accept="image/*, .pdf"
              :before-upload="beforeUpload"
              :on-success="fileUploadSuccess"
              :file-list="fileList"
            >
              <p>
                <img
                  src="@/assets/img/relevance_file.png"
                  style="vertical-align: middle"
                />
                上传附件
              </p>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer">
      <el-button @click="show = false">取 消</el-button>
      <el-button
        v-if="handle != 'detail'"
        type="primary"
        :loading="loading"
        @click="submitForm"
      >
        确 定
      </el-button>
    </div>
  </el-dialog>
</template>
<script>
import axios from "axios";
import { crmFileSaveUrl } from "@/api/common";
import {
  getCustomer,
  saveInvoice,
  getInvoiceMoney,
  updateInvoice,
} from "@/api/customermanagement/invoice";
import { getDivisionData } from "@/api/systemManagement/division";
export default {
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    form: {
      type: Object,
      default: () => {},
    },
    showDetail: {
      type: Boolean,
      default: false,
    },
    handle: {
      type: String,
      default: "detail",
    },
  },
  data() {
    return {
      editForm: {
        department: "", // 部门
        order_type: "正常开票", // 订单类型
        customer_id: "", // 客户id
        invoice_unit: "", // 开票单位
        invoice_type: "普票", // 发票类型
        service_name: "", // 货物及应税劳务
        detail: [], // 开票订单列表
        customer_unit: "", // 客户单位
        specification_model: "", // 规格型号
        pay_duty_number: "", // 纳税识别号
        invoice_money: "", // 开票金额
        remark: "", // 备注
        attachment: "", // 附件
      },
      dataList: [], // 开票订单列表
      fileList: [], // 附件列表
      formRules: {
        department: [{ required: true, message: "请选择部门", trigger: "change" }],
        order_type: [{ required: true, message: "请选择订单类型", trigger: "change" }],
        customer_id: [{ required: true, message: "请选择客户", trigger: "change" }],
        invoice_unit: [{ required: true, message: "请选择开票单位", trigger: "change" }],
        invoice_type: [{ required: true, message: "请选择发票类型", trigger: "change" }],
        service_name: [
          { required: true, message: "请选择货物及应税劳务", trigger: "change" },
        ],
        customer_unit: [{ required: true, message: "请输入客户单位", trigger: "blur" }],
        specification_model: [
          { required: true, message: "请输入规格型号", trigger: "blur" },
        ],
        pay_duty_number: [
          { required: true, message: "请输入纳税识别号", trigger: "blur" },
        ],
      },
      loading: false, // 加载状态
      divisionList: [], // 部门列表
      orderTypeList: ["正常开票", "先票后款"], // 订单类型列表
      customerList: [], // 客户列表
      invoiceUnitList: [
        "四川轻账财税服务有限公司",
        "纵横云海财税服务(成都)有限公司",
        "成都轻账管家企业管理有限公司",
        "四川轻账科技有限公司",
      ],
      invoiceTypeList: ["普票", "专票"], // 发票类型列表
      serviceList: [
        "纳税申报代理（代账&报税）",
        "一般税务咨询（税优、短期等）",
        "其他经纪代理服务（办件类）",
        "其他税务事项代理（仅代账）",
        "其他咨询服务（财税类不可选）",
      ], // 货物及应税劳务列表
      contractList: [], // 合同列表
    };
  },
  computed: {
    show: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit("input", val);
      },
    },
    // 附件上传地址
    crmFileSaveUrl() {
      return window.BASE_URL + crmFileSaveUrl;
    },
    // 请求头
    httpHeader() {
      return {
        authKey: axios.defaults.headers.authKey,
        sessionId: axios.defaults.headers.sessionId,
      };
    },
  },
  watch: {
    value(val) {
      if (val) {
        this.$nextTick(async () => {
          await this.getDivisionList()
          if (this.form.id) {
            Object.keys(this.form).forEach((key) => {
              if (this.form[key]) {
                this.editForm[key] = this.form[key];
              }
            });
            this.customerList = [
              { name: this.form.customer_name, customer_id: this.form.customer_id },
            ];
            this.dataList = this.form.detail || [];
            this.getCustomerList(this.form.customer_name);
            this.dataList.forEach((item) => {
              item.orderList = [{ order_sn: item.order_sn }];
            });
            this.fileList = this.form.attachment
              ? this.form.attachment.split(",").filter(Boolean)
              : [];
          }
        });
      }
    },
    dataList: {
      handler(val) {
        let money = 0;
        val.forEach((item) => {
          money += parseFloat(item.money || "0");
        });
        this.editForm.invoice_money = money.toFixed(2);
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    // 获取事业部列表
    getDivisionList() {
      return new Promise((resolve) => {
        getDivisionData().then(res => {
          let list = res.data.list;
          list = list.map(item => item.name)
          this.divisionList = list
          resolve()
        }).catch(() => {
          this.divisionList = []
          resolve()
        })
      })
    },
    // 关闭弹窗
    dialogClose() {
      this.show = false;
      this.loading = false;
      this.dataList = [];
      this.fileList = [];
      this.customerList = [];
      this.contractList = [];
      this.editForm = {
        department: "", // 部门
        order_type: "正常开票", // 订单类型
        customer_id: "", // 客户id
        invoice_unit: "", // 开票单位
        invoice_type: "普票", // 发票类型
        service_name: "", // 货物及应税劳务
        detail: [], // 开票订单列表
        customer_unit: "", // 客户单位
        specification_model: "", // 规格型号
        pay_duty_number: "", // 纳税识别号
        invoice_money: "", // 开票金额
        remark: "", // 备注
        attachment: "", // 附件
      };
      this.$refs.formRef.resetFields();
      this.$emit("on-close");
    },
    // 新增开票订单
    addData() {
      let valids = [];
      this.$refs.formRef.validateField(["department", "customer_id"], (valid) => {
        if (!valid) {
          valids.push(valid);
          if (valids.length == 2 && valids.every((i) => !i)) {
            this.dataList.push({
              contract_id: "", // 合同ID
              order_sn: "", // 回款编号
              orderList: [], // 回款编号列表
              total_money: "", // 总金额
              used_money: "", // 已开票金额
              money: "", // 开票金额
            });
          }
        }
      });
    },
    // 删除开票订单
    delData(index) {
      this.dataList.splice(index, 1);
    },
    // 查看详情
    handleContract(row) {
      if (!this.showDetail) return;
      this.$emit("on-detail", row);
    },
    // 清空客户相关信息
    changeOrderType() {
      this.editForm.customer_id = "";
      this.customerList = [];
      this.dataList = [];
    },
    // 获取客户列表
    getCustomerList(customer_name = "") {
      getCustomer({
        customer_name,
        order_type: this.editForm.order_type,
      }).then((res) => {
        this.customerList = res.data || [];
        if (this.handle === "edit") {
          let row = this.customerList.find((i) => i.customer_id == this.form.customer_id);
          this.contractList = (row && row.contract) || [];
        }
      });
    },
    // 选择客户
    changeCustomer(customer_id) {
      let row = this.customerList.find((i) => i.customer_id == customer_id);
      this.contractList = (row && row.contract) || [];
      this.dataList = [];
      this.addData();
    },
    // 选择回款编号
    changeOrderSn(order_sn = "", index) {
      if (this.handle === "add") {
        let row = this.dataList[index].orderList.find((i) => i.order_sn == order_sn);
        this.dataList[index].total_money = row.total_money || "0";
        this.dataList[index].used_money = row.used_money || "0";
        this.dataList[index].money = "";
      }
    },
    // 切换合同获取回款编号列表
    changeReceipt(contract_id = "", index) {
      this.dataList[index].order_sn = "";
      this.dataList[index].total_money = "";
      this.dataList[index].used_money = "";
      this.dataList[index].money = "";
      if (contract_id) {
        getInvoiceMoney({
          contract_id,
          department: this.editForm.department,
        }).then((res) => {
          this.dataList[index].orderList = res.data || [];
          if (this.editForm.order_type == "先票后款" && res.data.length == 1) {
            let row = res.data[0];
            this.dataList[index].total_money = row.total_money || "0";
            this.dataList[index].used_money = row.used_money || "0";
            this.dataList[index].money = "";
          }
        });
      } else {
        this.dataList[index].orderList = [];
      }
    },
    // 校验
    beforeUpload(file) {
      let size = file.size / 1024 / 1024;
      if (size > 100) {
        this.$message.error("文件大小不能超过100M");
        return false;
      }
      let type = file.name.split(".")[1];
      let types = ["jpg", "png", "jpeg", "gif", "bmp", "pdf"];
      if (!types.includes(type)) {
        this.$message.error("文件格式不正确");
        return false;
      }
      return true;
    },
    // 上传成功
    fileUploadSuccess(res, file, fileList) {
      this.fileList = fileList;
    },
    // 预览图片
    previewImage(index) {
      this.$bus.emit("preview-image-bus", {
        index: index,
        data: this.fileList.map((item) => {
          return {
            url: item,
            name: item.substr(item.lastIndexOf("/") + 1),
          };
        }),
      });
    },
    // 提交表单
    submitForm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          let data = Object.assign({}, this.editForm);
          if (Number(data.total_money) <= 0) {
            this.$message.error("开票金额不能为0");
            return;
          }
          data.detail = this.dataList
            .filter((i) => i.contract_id)
            .map(({ orderList, status, invoice_id, ...i }) => i);
          data.attachment = this.fileList.map((i) => i.response.data[0].path).join(",");
          const request = this.handle === "add" ? saveInvoice : updateInvoice;
          this.loading = true;
          request(data)
            .then((res) => {
              this.$message.success(res.data || "操作成功");
              this.$emit("on-success");
              this.dialogClose();
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.atta-img {
  width: 100px;
  height: 100px;
  object-fit: cover;
  margin-bottom: 10px;
  margin-right: 10px;
}
::v-deep .receivable .el-input--suffix .el-input__inner {
  padding-right: 8px !important;
}
</style>
